<?php

namespace catchAdmin\visitPlan\model;

use app\common\lib\ZhyxMongo;
use app\common\model\BaseModel;
use catchAdmin\visitPlan\search\VisitPlanDetailSearch;
use catcher\CatchResponse;


class VisitPlanDetail extends BaseModel
{
    use VisitPlanDetailSearch;

    public $name = 'visit_plan_detail';

    public function getLists(string $id, int $type): array
    {
        $postData = request()->param();
        $page = request()->param("page", 1, "int");
        $limit = request()->param("limit", 15, "int");

        $data = [];
        $collection = ZhyxMongo::getInstance()->setCollection('visit_plan_detail');
        $match = [];
        if (isset($postData["patientName"]) && !empty(trim($postData["patientName"]))) {
            $match["patientName"] = ['$regex' => trim($postData["patientName"])];
        }
        if (isset($postData["push_type"]) && !empty(trim($postData["push_type"]))) {
            $match["push_type"] = $postData["push_type"];
        }
        if (isset($postData["push_status"]) && !empty(trim($postData["push_status"]))) {
            $match["push_status"] = $postData["push_status"];
        }

        switch ($type) {
            case "1":
                $match["next_visit_time"] = date("Y-m-d");
                $match["visit_status"] = 1;
                break;
            case "2":
                $match["visit_status"] = 0;
                $match["next_visit_time"] = ['$gte' => date("Y-m-d")];
                break;
            case "3":
                $match["next_visit_time"] = ['$lt' => date("Y-m-d")];
                $match["visit_status"] = 0;
                break;
            case "4":
                $match["visit_status"] = 1;
                break;
        }

        $pipLine = [['$match' => ['visit_id' => $id]], ['$unwind' => ['path' => '$plan_list', 'preserveNullAndEmptyArrays' => true]], ['$sort' => ['plan_list.plan_visit_date' => -1]], ['$group' => ['_id' => '$patientId', 'patientName' => ['$first' => '$patientName'], 'sex' => ['$first' => '$sex'], 'inage' => ['$first' => '$inage'], 'presentTelphone' => ['$first' => '$presentTelphone'], 'outhospitalDeptCode' => ['$first' => '$outhospitalDeptCode'], 'outhospitalDate' => ['$first' => '$outhospitalDate'], 'diagnosis' => ['$first' => '$diagnosis'], 'next_visit_time' => ['$first' => '$plan_list.plan_visit_date'], 'visit_dept' => ['$first' => '$visit_dept'], 'push_status' => ['$first' => '$plan_list.push_status'], 'period_content' => ['$first' => '$period_content'], 'id' => ['$first' => ['$toString' => '$_id']], 'push_type' => ['$first' => '$push_type'], 'visit_status' => ['$first' => '$plan_list.visit_status'], 'is_stop' => ['$first' => '$is_stop'], 'come_visit_date' => ['$first' => '$plan_list.come_visit_date']]], ['$match' => $match]];

        $countPipLine = array_merge($pipLine, [['$count' => "total_count"]]);

        $totalCountCursor = iterator_to_array($collection->aggregate($countPipLine));

        if (!empty($totalCountCursor) && $totalCountCursor[0]["total_count"] > 0) {

            $dataPipLine = array_merge($pipLine, [['$skip' => ($page - 1) * $limit], ['$limit' => $limit]]);
            $data = iterator_to_array(ZhyxMongo::getInstance()->setCollection('visit_plan_detail')->aggregate($dataPipLine));

        }

        return [
            "count" => $totalCountCursor[0]["total_count"] ?? 0,
            "current" => $page,
            "limit" => $limit,
            "data" => $data
        ];

    }

    public function getPushTypeTextAttr($value, $data): string
    {
        $statusTextArr = ["ALL" => "APP/短信", "APP" => "app", "SMS" => "短信"];
        return $statusTextArr[$data["push_type"]];
    }

    public function getStatusTextAttr($value, $data): string
    {
        $statusTextArr = [0 => "未推送", 1 => "推送成功", 2 => "推送失败"];
        return $statusTextArr[$data["status"]];
    }


    public function getHomeList()
    {
        $result = $this->mongoSearch([], ["patientName", "status", "push_type", "visit_id"]);
        $uidArr = $this->getUserIds();
        if (!empty($uidArr)) {
            $result = $result->where("creator_id", "in", $uidArr);
        }
        return $result->field('visit_dept.dept_name,patientName,created_at')->order('created_at', 'desc')->select()->toArray();
    }

    public function getVisitCount(string $planId)
    {

        $collection = ZhyxMongo::getInstance()->setCollection('visit_plan_detail');
        $cursor = $collection->aggregate([['$match' => ['visit_id' => $planId]], ['$unwind' => ['path' => '$plan_list', 'preserveNullAndEmptyArrays' => true]], ['$sort' => ['plan_list.plan_visit_date' => -1]], ['$group' => ['_id' => '$patientId', 'visit_status' => ['$first' => '$plan_list.visit_status'], 'plan_visit_date' => ['$first' => '$plan_list.plan_visit_date']]], ['$group' => ['_id' => null, 'total_patient' => ['$sum' => 1], 'wait_visit' => ['$sum' => ['$cond' => [['$and' => [['$eq' => ['$visit_status', 0]], ['$gte' => ['$plan_visit_date', date("Y-m-d")]]]], 1, 0]]], 'today_visit' => ['$sum' => ['$cond' => [['$and' => [['$eq' => ['$visit_status', 1]], ['$eq' => ['$plan_visit_date', date("Y-m-d")]]]], 1, 0]]], 'no_visit' => ['$sum' => ['$cond' => [['$and' => [['$eq' => ['$visit_status', 0]], ['$lt' => ['$plan_visit_date', date("Y-m-d")]]]], 1, 0]]], 'visit' => ['$sum' => ['$cond' => [['$eq' => ['$visit_status', 1]], 1, 0]]]]]], ['$project' => ['_id' => false]]);
        return iterator_to_array($cursor)[0] ?? [];

    }

    public function getRevisitStatusAttr($value, $data): string
    {
        $statusText = "";
        $nextVisitTime = $data["next_visit_time"];
        $status = $data["status"];
        if ($status === 0) {
            if ($nextVisitTime < date("Y-m-d")) {
                $statusText = "未复诊";
            } else {
                $statusText = "待复诊";
            }
        } else {
            $statusText = "已复诊";
        }
        return $statusText;
    }

    public function getPeriodTextAttr($value, $data): string
    {

        $weekValue = ["1" => "一周", "2" => "半个月", "3" => "一个月", "4" => "一季度", "5" => "半年", "6" => "年"];
        return $weekValue[$data["period"]] ?? "无";
    }

    public function getDetailListByPatientId(string $patientId, array $date): array
    {
        $result = $this->where([["patientId", "=", $patientId], ["plan_list.push_status", "=", 1]]);
        if (!empty($date)) {
            $result = $result->whereBetweenTime('next_visit_time', $date[0], $date[1]);
        }

        $result = $result->order("id", "desc")->select();
        if (!empty($result)) {
            foreach ($result as $k => &$v) {
                $next_visit_time = null;
                foreach ($v['plan_list'] as $plan) {
                    // 检查 push_status 是否为 1
                    if ($plan['push_status'] == 1) {
                        // 更新最大日期
                        if ($next_visit_time === null || $plan['plan_visit_date'] > $next_visit_time) {
                            $next_visit_time = $plan['plan_visit_date'];
                        }
                    }
                }
                $v["next_visit_time"] = $next_visit_time;
            }
            $result->visible(["id", "push_date", "next_visit_time", "visit_name", "creator_name", "visit_finish_time", "visit_dept", "period_content", "period", "remind_count"])->append(["revisit_status", "period_text"]);

        }

        return $result->toArray();
    }


}